package abraham;
import java.io.*;
public class BitsWriter {
	private String filename;
	
	private byte[] buffer=new byte[8];
	private byte[] outByte=new byte[1];
	private int pointer=0;
	private BufferedOutputStream bw;
	public BitsWriter(){
	
	}
	public void Close() throws IOException{
		if(pointer!=0)
		{
			for(int i=pointer;i<=7;i++)
				buffer[i]=0;
			OutputBufferToFile();
		}
		bw.close();
	}
	private void OutputBufferToFile() throws IOException{
		byte out=0;
		for(int i=7;i>=0;i--){
			out<<=1;
			out|=buffer[i];
		}
		outByte[0]=out;
		bw.write(outByte);
	}
	public void AppendBits(String value) throws IOException{
		for(int i=0;i<value.length();i++){
			if(value.charAt(i)=='0'){
				buffer[pointer]=0;
			}else
				buffer[pointer]=1;
			pointer++;
			if(pointer==8){
				OutputBufferToFile();
				pointer=0;
			}
			
		}
	}
	
	public void OpenFile(String filename) throws FileNotFoundException{
		this.filename=filename;
		FileOutputStream fos=new FileOutputStream(filename);
		bw=new BufferedOutputStream(fos);
	}
}
